package com.boot.main.service.impl;

import com.boot.main.entity.CcomUser;
import com.boot.main.entity.ScomShop;
import com.boot.main.mapper.CcomUserMapper;
import com.boot.main.mapper.ScomShopMapper;
import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.IShopService;
import com.boot.main.utils.IsNotEmptyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShopService implements IShopService {
    @Resource
    private ScomShopMapper shopMapper;

    @Resource
    private CcomUserMapper userMapper;

    public Long getUserId(){
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals =  subject.getPrincipals();
        String username = (String) principals.getPrimaryPrincipal();
        CcomUser user = userMapper.getUserByUserName(username);
        Long id = user.getId();
        return id;
    }

    @Override
    public ResponseData getShops(Integer page, Integer limit, String name){
        Long userId = getUserId();
        List<ScomShop> items = shopMapper.getShops((page-1)*limit, limit, name, userId);
        Integer count = shopMapper.getTotalCount();
        Map map = new HashMap();
        map.put("datas",items);
        map.put("count", count);
        return ResponseDataUtil.success("获取店铺成功", map);
    }

    @Override
    public ResponseData getAdminShops(Integer page, Integer limit, String name){
        CcomUser user = userMapper.getUserByUserName("superAdmin");
        List<ScomShop> items = shopMapper.getShops((page-1)*limit, limit, name, user.getId());
        Integer count = shopMapper.getTotalCount();
        Map map = new HashMap();
        map.put("datas",items);
        map.put("count", count);
        return ResponseDataUtil.success("获取店铺成功", map);
    }

    @Override
    public ResponseData saveShop(ScomShop shop){
        Integer num = shopMapper.saveShop(shop);
        if(IsNotEmptyUtil.isEmpty(num)){
            return ResponseDataUtil.error("保存店铺失败", null);
        }
        return ResponseDataUtil.success("保存店铺成功", null);
    }

    @Override
    public ResponseData updateShop(ScomShop shop){
        Integer num = shopMapper.updateShop(shop);
        if(IsNotEmptyUtil.isEmpty(num)){
            return ResponseDataUtil.error("修改店铺失败", null);
        }
        return ResponseDataUtil.success("修改店铺成功", null);
    }

    @Override
    public ResponseData deleteShop(Long id){
        Integer num = shopMapper.deleteShop(id);
        return ResponseDataUtil.success("删除店铺成功", null);
    }
}
